import { useHistory, useLocation } from 'react-router-dom'
import { InfiniteScroll, NavBar } from 'antd-mobile'

import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getSearchResults } from '@/store/actions/search'
import { RootState } from '@/types/store'
// import { getArticleDetail } from '@/store/actions/articles'
import ArticleItem from '@/pages/Home/components/ArticleItem'

const Result = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // const params = useParams<{ id: string }>()

  //---请求搜索详情页数据--------
  const location = useLocation()
  const params = new URLSearchParams(location.search)
  const key = params.get('key')
  const { results, page, total_count } = useSelector(
    (state: RootState) => state.search.resultsObj
  )

  //----------
  // 是否有更多数据
  const [hasMore, setHasMore] = useState(true)
  // 加载状态
  const [isLoading, setLoading] = useState(false)

  const loadMore = async () => {
    // 有关键字, 不在loading中, 才能进行请求
    if (key && !isLoading) {
      // 在准备发请求时, 立刻将 isLoading 改成 true
      setLoading(true)
      await dispatch(getSearchResults(page + 1, key))
      // 请求成功回来, 将 isLoading 改为 false
      setLoading(false)
    }
  }

  useEffect(() => {
    // 限制, 至多只能加载 5 页
    if (page + 1 > 5 || total_count === results.length) {
      // 没有更多了, 关闭加载更多的功能
      setHasMore(false)
    }
  }, [page, total_count, results])

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item) => (
          <div key={item.art_id} className="article-item">
            <ArticleItem article={item}></ArticleItem>
          </div>
        ))}
        {/* 无限加载 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </div>
    </div>
  )
}

export default Result
